package com.kgc.pay.controller;

import com.alibaba.dubbo.common.json.JSONObject;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import utils.WxResult;
import com.kgc.pay.service.*;
import java.util.Map;
import java.util.UUID;

@Controller
public class WeChatController {

    @Autowired
    private PayService payService;
    @RequestMapping("/wxpay/{out_trade_no}/{total_fee}")
    public String pay(
            @PathVariable("out_trade_no")String out_trade_no,
            @PathVariable("total_fee")String total_fee,
            Model model){
        //金额,单位为分
         total_fee="1";

        //out_trade_no根据号查询一个订单的状态
        Map map = payService.generaterQRious(out_trade_no, total_fee);
        model.addAttribute("map", map);
        return "qrious";
    }

    @RequestMapping("/wxPayStatus")
    @ResponseBody
    public WxResult wxPayStatus(String out_trade_no){
        WxResult result=null;
        //设置无限循环,目的是实时获取订单状态
        while (true) {
            Map map = payService.queryPayStatus(out_trade_no);
            if(map==null){
                result=new WxResult(false, "支付失败");
                break;
            }
            if(map.get("trade_state").equals("SUCCESS")){
                result=new WxResult(true, "支付成功");

                break;
            }
            //加入定时器,10s查询一次
            try {
                Thread.sleep(10000);
            }catch (Exception ex){
                ex.printStackTrace();
            }
        }
        if(result.isSuccess()){
            //支付成功
        }else{
            //支付失败
        }
     return result;
    }
}
